package com.gy.paidao.util;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：gy on 16/5/4
 * 说明：
 */
public class GoogleLocationUtil {

    private Context context;
    private String provider;
    private LocationManager locationManager;
    private LocationListener locationListener;
    private List<OnLocationListener> locationListeners = new ArrayList<OnLocationListener>();

    private static GoogleLocationUtil instance;

    public static GoogleLocationUtil getInstance(Context context) {
        if (instance == null) {
            instance = new GoogleLocationUtil(context);
        }
        return instance;
    }

    private GoogleLocationUtil(Context context) {
        this.context = context;
        startLocation();
    }

    /**
     * 添加定位监听
     */
    public void addLocationListener(OnLocationListener listener) {
        if (listener == null) {
            throw new NullPointerException("OnLocationListener is null");
        }
        locationListeners.add(listener);

    }

    private void startLocation() {
        // 获取位置管理服务
        String serviceName = Context.LOCATION_SERVICE;
        locationManager = (LocationManager) context.getSystemService(serviceName);
//        locationManager.setTestProviderEnabled("gps", true);

        // 查找到服务信息
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        // 高精度
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_HIGH);

        provider = locationManager.getBestProvider(criteria, true);
        Location location = locationManager.getLastKnownLocation(provider);

        if (location != null) {
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            for (OnLocationListener listener : locationListeners) {
                listener.onAmapLocationListener(location);
            }
        }


        locationListener = new LocationListener() {
            public void onLocationChanged(Location location) {
                updateToNewLocation(location);
                for (OnLocationListener listener : locationListeners) {
                    listener.onAmapLocationListener(location);
                }
                locationListeners.clear();
            }

            public void onProviderDisabled(String provider) {
                updateToNewLocation(null);
                for (OnLocationListener listener : locationListeners) {
                    listener.onAmapLocationFail();
                }
                locationListeners.clear();
            }

            public void onProviderEnabled(String provider) {
            }

            public void onStatusChanged(String provider, int status, Bundle extras) {

            }
        };

        // 设置监听器，自动更新的最小时间为间隔N秒(1秒为1*1000，这样写主要为了方便)或最小位移变化超过N米
        //locationManager.requestLocationUpdates(provider, 5*1000, 0,locationListener);
        //locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000,0,locationListener);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5 * 60 * 10, 0, locationListener);

    }

    private void updateToNewLocation(Location location) {
        if (location != null) {
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            LogUtil.e("维度：" + latitude + "  经度" + longitude);

        } else {
            Toast.makeText(context, "无法获取地理信息", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 接收定位结果
     */
    public interface OnLocationListener {
        public void onAmapLocationListener(Location aMapLocation);

        public void onAmapLocationFail();
    }

}
